package com.app.micaihu.view.utils;

import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.os.Build;
import android.text.TextUtils;
import android.util.ArrayMap;
import android.view.View;

import androidx.core.app.NotificationCompat;
import androidx.fragment.app.FragmentManager;

import com.app.micaihu.R;
import com.app.micaihu.app.AppApplication;
import com.app.micaihu.bean.game.GameDownloadEntity;
import com.app.micaihu.bean.game.IDownload;
import com.app.micaihu.custom.components.downandupload.DownloadUtils;
import com.app.micaihu.db.NewsDBSqlHelper;
import com.app.micaihu.db.NewsDBUtil;
import com.app.micaihu.view.main.dialog.UnDownLoadGameDialogFragment;
import com.app.micaihu.view.main.dialog.UnInstallGameDialogFragment;
import com.app.micaihu.view.main.game.GameDownloadActivity;
import com.app.okhttplib.HttpInfo;
import com.app.okhttplib.OkHttpUtil;
import com.app.okhttplib.annotation.DownloadStatus;
import com.app.okhttplib.bean.DownloadFileInfo;
import com.blankj.utilcode.util.AppUtils;
import com.blankj.utilcode.util.CollectionUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.NetworkUtils;
import com.blankj.utilcode.util.NotificationUtils;
import com.blankj.utilcode.util.Utils;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class DownloadAgainUtils {
    /**
     *
     */
    public static void showGameDot(View gameDot) {
        if (gameDot == null) return;
        boolean haveUnInstallFile = false, haveUnDownLoadFile = false;
        List<Map<String, String>> cacheList = NewsDBUtil.getInstance().listCache(null, null, null, NewsDBSqlHelper.GAME_DOWNLOAD, null);
        if (cacheList != null) {
            int count = cacheList.size();
            List<GameDownloadEntity> list = new ArrayList<>();
            for (int i = count - 1; i >= 0; i--) {
                GameDownloadEntity gameDownloadEntity = new GameDownloadEntity();
                gameDownloadEntity.setId(cacheList.get(i).get("_id"));
                gameDownloadEntity.setName(cacheList.get(i).get("name"));
                gameDownloadEntity.setApp_url(cacheList.get(i).get("url"));
                gameDownloadEntity.setDescribe(cacheList.get(i).get("desc"));
                gameDownloadEntity.setLogo(cacheList.get(i).get("logo"));
                gameDownloadEntity.setPackageName(cacheList.get(i).get("packname"));
                gameDownloadEntity.setPath(cacheList.get(i).get("path"));
                gameDownloadEntity.setAppSize(cacheList.get(i).get("size"));
                list.add(gameDownloadEntity);
            }
            File unInstallFile;
            if (list != null) {
                for (GameDownloadEntity item : list) {
                    boolean appInstalled = AppUtils.isAppInstalled(item.getPackageName());
                    if (appInstalled) {
                        //已下载完成,安装完成
                    } else {
                        unInstallFile = new File(DownloadUtils.DOWNLOAD_FILEDIR, item.getIPath() + ".apk");
                        if (unInstallFile.exists() && unInstallFile.isFile()) {
                            //现在是已下载完成,准备安装
                            haveUnInstallFile = true;
                        } else {
                            haveUnDownLoadFile = true;
                        }
                    }
                }
                if (haveUnDownLoadFile || haveUnInstallFile) {
                    gameDot.setVisibility(View.VISIBLE);
                } else {
                    gameDot.setVisibility(View.GONE);
                }
            }

        }
    }

    public static void showDownLoadDialog(FragmentManager fragmentManager) {
        if (!AppApplication.isOpenApp) {
            boolean haveUnInstallFile = false, haveUnDownLoadFile = false;
            GameDownloadEntity gameItem = null;

            List<Map<String, String>> cacheList = NewsDBUtil.getInstance().listCache(null, null, null, NewsDBSqlHelper.GAME_DOWNLOAD, null);
            LogUtils.e("DownloadAgainUtils", cacheList);
            if (cacheList != null) {
                int count = cacheList.size();
                List<GameDownloadEntity> list = new ArrayList<>();
                for (int i = count - 1; i >= 0; i--) {
                    GameDownloadEntity gameDownloadEntity = new GameDownloadEntity();
                    gameDownloadEntity.setId(cacheList.get(i).get("_id"));
                    gameDownloadEntity.setName(cacheList.get(i).get("name"));
                    gameDownloadEntity.setApp_url(cacheList.get(i).get("url"));
                    gameDownloadEntity.setDescribe(cacheList.get(i).get("desc"));
                    gameDownloadEntity.setLogo(cacheList.get(i).get("logo"));
                    gameDownloadEntity.setPackageName(cacheList.get(i).get("packname"));
                    gameDownloadEntity.setPath(cacheList.get(i).get("path"));
                    gameDownloadEntity.setAppSize(cacheList.get(i).get("size"));
                    list.add(gameDownloadEntity);
                }
                File unInstallFile;
                if (list != null) {
                    for (GameDownloadEntity item : list) {
                        boolean appInstalled = AppUtils.isAppInstalled(item.getPackageName());
                        if (appInstalled) {
                            //已下载完成,安装完成
                        } else {
                            unInstallFile = new File(DownloadUtils.DOWNLOAD_FILEDIR, item.getIPath() + ".apk");
                            if (unInstallFile.exists() && unInstallFile.isFile()) {
                                //现在是已下载完成,准备安装
                                haveUnInstallFile = true;
                                gameItem = item;
                            } else {
                                haveUnDownLoadFile = true;
                            }
                            break;
                        }
                    }
                    LogUtils.e("DownloadAgainUtils", "haveUnInstallFile->" + haveUnInstallFile + "  haveUnDownLoadFile->" + haveUnDownLoadFile);
                    if (haveUnInstallFile) {
                        UnInstallGameDialogFragment.newInstance(gameItem).show(fragmentManager);
                    } else if (haveUnDownLoadFile) {
                        if (NetworkUtils.isWifiConnected()) {
                            ArrayMap<String, String> gameDownload = NewsDBUtil.getInstance().getGameDownload();
                            if (gameDownload.size() == 0) {
                                for (GameDownloadEntity item : list) {
                                    boolean appInstalled = AppUtils.isAppInstalled(item.getPackageName());
                                    if (appInstalled) {
                                        //已下载完成,安装完成
                                    } else {
                                        unInstallFile = new File(DownloadUtils.DOWNLOAD_FILEDIR, item.getIPath() + ".apk");
                                        if (unInstallFile.exists() && unInstallFile.isFile()) {
                                            //现在是已下载完成,准备安装
                                        } else {
                                            DownloadFileInfo downloadFileInfo = DownloadUtils.getSingleton().getDownloadFileInfo(OkHttpUtil.getTag(item.getIUrl()));
                                            if (downloadFileInfo == null) {
                                                DownloadUtils.getSingleton().down(item.getIUrl(), item.getIPath(), item);
                                            } else {
                                                if (!DownloadStatus.DOWNLOADING.equals(downloadFileInfo.getDownloadStatus())) {
                                                    DownloadUtils.getSingleton().down(item.getIUrl(), item.getIPath(), item);
                                                }
                                            }
                                        }
                                    }
                                }
                            } else {
                                for (GameDownloadEntity item : list) {
                                    if (!item.getIGameId().equals(gameDownload.get(item.getIGameId()))) {
                                        boolean appInstalled = AppUtils.isAppInstalled(item.getPackageName());
                                        if (appInstalled) {
                                            //已下载完成,安装完成
                                        } else {
                                            unInstallFile = new File(DownloadUtils.DOWNLOAD_FILEDIR, item.getIPath() + ".apk");
                                            if (unInstallFile.exists() && unInstallFile.isFile()) {
                                                //现在是已下载完成,准备安装
                                            } else {
                                                DownloadFileInfo downloadFileInfo = DownloadUtils.getSingleton().getDownloadFileInfo(OkHttpUtil.getTag(item.getIUrl()));
                                                if (downloadFileInfo == null) {
                                                    DownloadUtils.getSingleton().down(item.getIUrl(), item.getIPath(), item);
                                                } else {
                                                    if (!DownloadStatus.DOWNLOADING.equals(downloadFileInfo.getDownloadStatus())) {
                                                        DownloadUtils.getSingleton().down(item.getIUrl(), item.getIPath(), item);
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        } else {
                            UnDownLoadGameDialogFragment.newInstance().show(fragmentManager);
                        }
                    }
                }
                AppApplication.isOpenApp = true;
            }

        }
    }


    public static void downLoadGame() {
        boolean haveUnInstallFile = false, haveUnDownLoadFile = false;

        List<Map<String, String>> cacheList = NewsDBUtil.getInstance().listCache(null, null, null, NewsDBSqlHelper.GAME_DOWNLOAD, null);
        LogUtils.e("DownloadAgainUtils", cacheList);
        if (cacheList != null) {
            int count = cacheList.size();
            List<GameDownloadEntity> list = new ArrayList<>();
            for (int i = count - 1; i >= 0; i--) {
                GameDownloadEntity gameDownloadEntity = new GameDownloadEntity();
                gameDownloadEntity.setId(cacheList.get(i).get("_id"));
                gameDownloadEntity.setName(cacheList.get(i).get("name"));
                gameDownloadEntity.setApp_url(cacheList.get(i).get("url"));
                gameDownloadEntity.setDescribe(cacheList.get(i).get("desc"));
                gameDownloadEntity.setLogo(cacheList.get(i).get("logo"));
                gameDownloadEntity.setPackageName(cacheList.get(i).get("packname"));
                gameDownloadEntity.setPath(cacheList.get(i).get("path"));
                gameDownloadEntity.setAppSize(cacheList.get(i).get("size"));
                list.add(gameDownloadEntity);
            }
            File unInstallFile;
            if (list != null) {
                for (GameDownloadEntity item : list) {
                    boolean appInstalled = AppUtils.isAppInstalled(item.getPackageName());
                    if (appInstalled) {
                        //已下载完成,安装完成
                    } else {
                        unInstallFile = new File(DownloadUtils.DOWNLOAD_FILEDIR, item.getIPath() + ".apk");
                        if (unInstallFile.exists() && unInstallFile.isFile()) {
                            //现在是已下载完成,准备安装
                            haveUnInstallFile = true;
                        } else {
                            haveUnDownLoadFile = true;
                        }
                        break;
                    }
                }
                LogUtils.e("DownloadAgainUtils", "haveUnInstallFile->" + haveUnInstallFile + "  haveUnDownLoadFile->" + haveUnDownLoadFile);
                if (haveUnDownLoadFile) {
                    ArrayMap<String, String> gameDownload = NewsDBUtil.getInstance().getGameDownload();
                    if (gameDownload.size() == 0) {
                        for (GameDownloadEntity item : list) {
                            boolean appInstalled = AppUtils.isAppInstalled(item.getPackageName());
                            if (appInstalled) {
                                //已下载完成,安装完成
                            } else {
                                unInstallFile = new File(DownloadUtils.DOWNLOAD_FILEDIR, item.getIPath() + ".apk");
                                if (unInstallFile.exists() && unInstallFile.isFile()) {
                                    //现在是已下载完成,准备安装
                                } else {
                                    DownloadFileInfo downloadFileInfo = DownloadUtils.getSingleton().getDownloadFileInfo(OkHttpUtil.getTag(item.getIUrl()));
                                    if (downloadFileInfo == null) {
                                        DownloadUtils.getSingleton().down(item.getIUrl(), item.getIPath(), item);
                                    } else {
                                        if (!DownloadStatus.DOWNLOADING.equals(downloadFileInfo.getDownloadStatus())) {
                                            DownloadUtils.getSingleton().down(item.getIUrl(), item.getIPath(), item);
                                        }
                                    }
                                }
                            }
                        }
                    } else {
                        for (GameDownloadEntity item : list) {
                            if (!item.getIGameId().equals(gameDownload.get(item.getIGameId()))) {
                                boolean appInstalled = AppUtils.isAppInstalled(item.getPackageName());
                                if (appInstalled) {
                                    //已下载完成,安装完成
                                } else {
                                    unInstallFile = new File(DownloadUtils.DOWNLOAD_FILEDIR, item.getIPath() + ".apk");
                                    if (unInstallFile.exists() && unInstallFile.isFile()) {
                                        //现在是已下载完成,准备安装
                                    } else {
                                        DownloadFileInfo downloadFileInfo = DownloadUtils.getSingleton().getDownloadFileInfo(OkHttpUtil.getTag(item.getIUrl()));
                                        if (downloadFileInfo == null) {
                                            DownloadUtils.getSingleton().down(item.getIUrl(), item.getIPath(), item);
                                        } else {
                                            if (!DownloadStatus.DOWNLOADING.equals(downloadFileInfo.getDownloadStatus())) {
                                                DownloadUtils.getSingleton().down(item.getIUrl(), item.getIPath(), item);
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }

    }

    public static int pauseDownLoadGame() {
        int downLoadSize = 0;
        boolean haveUnInstallFile = false, haveUnDownLoadFile = false;

        List<Map<String, String>> cacheList = NewsDBUtil.getInstance().listCache(null, null, null, NewsDBSqlHelper.GAME_DOWNLOAD, null);
        LogUtils.e("DownloadAgainUtils", cacheList);
        if (cacheList != null) {
            int count = cacheList.size();
            List<GameDownloadEntity> list = new ArrayList<>();
            for (int i = count - 1; i >= 0; i--) {
                GameDownloadEntity gameDownloadEntity = new GameDownloadEntity();
                gameDownloadEntity.setId(cacheList.get(i).get("_id"));
                gameDownloadEntity.setName(cacheList.get(i).get("name"));
                gameDownloadEntity.setApp_url(cacheList.get(i).get("url"));
                gameDownloadEntity.setDescribe(cacheList.get(i).get("desc"));
                gameDownloadEntity.setLogo(cacheList.get(i).get("logo"));
                gameDownloadEntity.setPackageName(cacheList.get(i).get("packname"));
                gameDownloadEntity.setPath(cacheList.get(i).get("path"));
                gameDownloadEntity.setAppSize(cacheList.get(i).get("size"));
                list.add(gameDownloadEntity);
            }
            File unInstallFile;
            if (list != null) {
                for (GameDownloadEntity item : list) {
                    boolean appInstalled = AppUtils.isAppInstalled(item.getPackageName());
                    if (appInstalled) {
                        //已下载完成,安装完成
                    } else {
                        unInstallFile = new File(DownloadUtils.DOWNLOAD_FILEDIR, item.getIPath() + ".apk");
                        if (unInstallFile.exists() && unInstallFile.isFile()) {
                            //现在是已下载完成,准备安装
                            haveUnInstallFile = true;
                        } else {
                            haveUnDownLoadFile = true;
                        }
                        break;
                    }
                }
                LogUtils.e("DownloadAgainUtils", "haveUnInstallFile->" + haveUnInstallFile + "  haveUnDownLoadFile->" + haveUnDownLoadFile);
                if (haveUnDownLoadFile) {
                    ArrayMap<String, String> gameDownload = NewsDBUtil.getInstance().getGameDownload();
                    if (gameDownload.size() == 0) {
                        for (GameDownloadEntity item : list) {
                            boolean appInstalled = AppUtils.isAppInstalled(item.getPackageName());
                            if (appInstalled) {
                                //已下载完成,安装完成
                            } else {
                                unInstallFile = new File(DownloadUtils.DOWNLOAD_FILEDIR, item.getIPath() + ".apk");
                                if (unInstallFile.exists() && unInstallFile.isFile()) {
                                    //现在是已下载完成,准备安装
                                } else {
                                    DownloadFileInfo downloadFileInfo = DownloadUtils.getSingleton().getDownloadFileInfo(OkHttpUtil.getTag(item.getIUrl()));
                                    if (downloadFileInfo != null) {
                                        if (DownloadStatus.DOWNLOADING.equals(downloadFileInfo.getDownloadStatus()) || DownloadStatus.PAUSE.equals(downloadFileInfo.getDownloadStatus())) {
                                            downLoadSize++;
                                        }
                                        if (!DownloadStatus.PAUSE.equals(downloadFileInfo.getDownloadStatus())) {
                                            downloadFileInfo.setDownloadStatus(DownloadStatus.PAUSE);
                                        }
                                    }

                                }
                            }
                        }
                    } else {
                        for (GameDownloadEntity item : list) {
                            if (!item.getIGameId().equals(gameDownload.get(item.getIGameId()))) {
                                boolean appInstalled = AppUtils.isAppInstalled(item.getPackageName());
                                if (appInstalled) {
                                    //已下载完成,安装完成
                                } else {
                                    unInstallFile = new File(DownloadUtils.DOWNLOAD_FILEDIR, item.getIPath() + ".apk");
                                    if (unInstallFile.exists() && unInstallFile.isFile()) {
                                        //现在是已下载完成,准备安装
                                    } else {
                                        DownloadFileInfo downloadFileInfo = DownloadUtils.getSingleton().getDownloadFileInfo(OkHttpUtil.getTag(item.getIUrl()));
                                        if (downloadFileInfo != null) {
                                            if (DownloadStatus.DOWNLOADING.equals(downloadFileInfo.getDownloadStatus()) || DownloadStatus.PAUSE.equals(downloadFileInfo.getDownloadStatus())) {
                                                downLoadSize++;
                                            }
                                            if (!DownloadStatus.PAUSE.equals(downloadFileInfo.getDownloadStatus())) {
                                                downloadFileInfo.setDownloadStatus(DownloadStatus.PAUSE);
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }

        return downLoadSize;
    }

    public static NotificationManager manager;
    public static NotificationChannel notificationChannel;
    public static NotificationCompat.Builder builder;


    public static NotificationManager getManager() {
        if (manager == null) {
            manager = (NotificationManager) Utils.getApp().getSystemService(Context.NOTIFICATION_SERVICE);
        }
        return manager;
    }


    /**
     * 通知栏弹窗
     */
    public static void showNotification(Context context, IDownload iDownload, int progress) {
        if (iDownload == null) return;
        String iGameId = iDownload.getIGameId();
        getManager();
        //判断是否是8.0Android.O
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            if (notificationChannel == null) {
                notificationChannel = new NotificationChannel("static", "download", NotificationManager.IMPORTANCE_MIN);
            }
            manager.createNotificationChannel(notificationChannel);
        }
        if (builder == null) {
            builder = new NotificationCompat.Builder(context, "static");
        }
        builder.setProgress(100, progress, false);
        builder.setContentTitle("正在下载 " + iDownload.getITitle() + " " + progress + "%");
        builder.setSmallIcon(R.drawable.push_small);
        builder.setOngoing(true);
        //大图标
        builder.setLargeIcon(BitmapFactory.decodeResource(AppApplication.getInstance().getResources(), R.mipmap.icon));
//        builder.setColor(Color.parseColor("#000000"));//设置icon 的背景颜色
//        builder.setAutoCancel(true);
        //设置intent.如果有url,则直接跳转url
        Intent intent = new Intent();
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setClass(context, GameDownloadActivity.class);
        int pendingIntentId = (int) (System.currentTimeMillis() / 1000);
        PendingIntent pendingIntent = PendingIntent.getActivity(context, pendingIntentId, intent, PendingIntent.FLAG_UPDATE_CURRENT);
        builder.setContentIntent(pendingIntent);

        int articleIdInt = Long.valueOf(iGameId).intValue();
        Notification notification = builder.build();
        notification.flags |= Notification.FLAG_ONLY_ALERT_ONCE;
        manager.notify(articleIdInt, notification);

    }

}
